package com.hypo.business.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hypo.business.domain.Result;
import com.hypo.business.domain.User;
import com.hypo.business.domain.dto.LoginInfoDto;
import com.hypo.business.domain.dto.PageResultDto;
import com.hypo.business.domain.vo.UserInfoVo;
import com.hypo.business.domain.vo.UserLoginVo;
import com.hypo.business.domain.vo.UserQueryParamVo;
import com.hypo.business.service.UserService;
import com.hypo.utils.AESUtils;
import com.hypo.utils.RSAUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.security.KeyPair;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author hypo
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    public static final String key = "9439db3bdc084fc9";
    //生成RSA密钥对
    private static KeyPair keyPair;

    static {
        try {
            keyPair = RSAUtil.generateRSAKeyPair();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除角色信息
     */
    @DeleteMapping
    public Result delete(@RequestParam List<Long> userIds) {
        userService.removeByIds(userIds);
        return Result.success();
    }

    /**
     * 修改角色信息
     */
    @PutMapping("/{userId}")

    public Result update(@RequestBody UserInfoVo vo, @PathVariable("userId") Long userId) {
        User user = new User();
        BeanUtils.copyProperties(vo, user);
        user.setUserId(userId);
        userService.updateById(user);
        return Result.success();
    }

    /**
     * 添加角色信息
     */
    //@PostMapping
    //public Result save(@RequestBody UserInfoVo vo) throws Exception {
    //    List<User> list = userService.list(Wrappers.<User>lambdaQuery()
    //            .eq(User::getUserName, vo.getUserName()));
    //    if (CollUtil.isEmpty(list)) {
    //        User user = new User();
    //        user.setUserPassword(vo.getPassword());
    //        BeanUtils.copyProperties(vo, user);
    //        //获取用户password
    //        String userPassword = user.getUserPassword();
    //        //对密码加密
    //        byte[] encryptPassword = RSAUtil.encrypt(userPassword, keyPair.getPublic());
    //        //使用Base64.encode转成字符串进行存储
    //        String encode = Base64.encode(encryptPassword);
    //        //设置加密密码
    //        user.setUserPassword(encode);
    //        user.setCreateTime(LocalDateTime.now());
    //        user.setUpdateTime(LocalDateTime.now());
    //        //存入数据库
    //        userService.save(user);
    //        return Result.success();
    //    } else {
    //        return Result.error("用户已存在");
    //    }
    //}
    @PostMapping
    public Result save(@RequestBody UserInfoVo vo) throws Exception {
        List<User> list = userService.list(Wrappers.<User>lambdaQuery()
                .eq(User::getUserName, vo.getUserName()));
        if (CollUtil.isEmpty(list)) {
            User user = new User();
            user.setUserPassword(vo.getPassword());
            BeanUtils.copyProperties(vo, user);
            //设置加密密码
            user.setUserPassword(AESUtils.encrypt(user.getUserPassword(), key));
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            //存入数据库
            userService.save(user);
            return Result.success();
        } else {
            return Result.error("用户已存在");
        }
    }

    /**
     * 分页条件查询
     */
    @GetMapping
    public Result pageQuery(UserQueryParamVo vo) {
        IPage<User> page = new Page<>(vo.getPage(), vo.getPageSize());
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!Objects.isNull(vo.getNickName()), User::getNickName, vo.getNickName())
                .eq(!Objects.isNull(vo.getGender()), User::getGender, vo.getGender())
                .eq(!Objects.isNull(vo.getStatus()), User::getStatus, vo.getStatus());
        IPage<User> pageInfo = userService.page(page, queryWrapper);
        long total = pageInfo.getTotal();
        List<User> result = pageInfo.getRecords();
        return Result.success(new PageResultDto<>(total, result));
    }

    /**
     * 登录
     *
     * @param vo 用户登录信息
     * @return 返回令牌
     */
    //@PostMapping("/login")
    //public Result login(@RequestBody UserLoginVo vo) throws Exception {
    //    //1.判断账号密码是否为空
    //    if (vo.getUserName() == null || vo.getUserPassword() == null) {
    //        return Result.error("用户名或密码不能为空");
    //    }
    //    //2.不为空执行查询
    //    User user = userService.getOne(Wrappers.<User>lambdaQuery()
    //            .eq(User::getUserName, vo.getUserName()));
    //    if (ObjectUtil.isEmpty(user)) {
    //        return Result.error("用户不存在");
    //    }
    //    String userPassword = user.getUserPassword();
    //    //Base64转成字节数组
    //    byte[] decode = Base64.decode(userPassword);
    //    String decrypt = RSAUtil.decrypt(decode, keyPair.getPrivate());
    //    if (decrypt.equals(vo.getUserPassword())) {
    //        LoginInfoDto loginInfo = userService.getToken(user);
    //        return Result.success(loginInfo);
    //    } else {
    //        return Result.error("账号或密码错误!");
    //    }
    //}
    @PostMapping("/login")
    public Result login(@RequestBody UserLoginVo vo) throws Exception {
        //1.判断账号密码是否为空
        if (vo.getUserName() == null || vo.getUserPassword() == null) {
            return Result.error("用户名或密码不能为空");
        }
        //2.不为空执行查询
        User user = userService.getOne(Wrappers.<User>lambdaQuery()
                .eq(User::getUserName, vo.getUserName()));
        if (ObjectUtil.isEmpty(user)) {
            return Result.error("用户不存在");
        }
        String decrypt = AESUtils.decrypt(user.getUserPassword(), key);
        if (decrypt.equals(vo.getUserPassword())) {
            LoginInfoDto loginInfo = userService.getToken(user);
            return Result.success(loginInfo);
        } else {
            return Result.error("账号或密码错误!");
        }
    }
}